﻿#include "stdafx.h"
#include "HChatMainDlg.h"
#include "QHostAddress"
#include "../PubTools/HMsgManager.h"
#include "HActionDefines.h"
#include "HMessageMaker.h"


HChatMainDlg::HChatMainDlg(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::QChatMainDlgClass())
{
    ui->setupUi(this);

    InitSlotFun();
}

HChatMainDlg::~HChatMainDlg()
{
    killTimer(m_GetUserListTimerId);

    delete ui;
}

void HChatMainDlg::OnSendMessage()
{
    HMsgManager& msgClient = HMsgManager::GetInstance();

    msgClient.DoSendMessage(m_pTcpSock, ui->lineEditUserName->text(), m_ClientToken, ui->textEditSendMsg->toPlainText());

    ui->textEditSendMsg->clear();
}

void HChatMainDlg::OnConnectSrv()
{
    QString strUserName = ui->lineEditUserName->text();

    if (strUserName.isEmpty())
    {
        QMessageBox::information(this, tr("提示"), tr("用户名不能为空"), QMessageBox::Ok);
        return;
    }

    QString strIp = ui->lineEditIP->text();
    QString strPort = ui->lineEditPort->text();
    int nPort = strPort.toInt();

    CloseConnection();

    if (m_pTcpSock == nullptr)
    {
        m_pTcpSock = new QTcpSocket(this);
    }

    m_pTcpSock->connectToHost(QHostAddress(strIp), nPort);

    connect(m_pTcpSock, &QTcpSocket::connected,
        [=]()
        {
            HMsgManager& msgClient = HMsgManager::GetInstance();

            msgClient.QueryUserName(m_pTcpSock, strUserName);
        }
    );

    connect(m_pTcpSock, &QTcpSocket::readyRead,
        [=]()
        {
            //获取对方发送的内容
            QByteArray strAction = m_pTcpSock->readAll();

            HMsgManager& msgClient = HMsgManager::GetInstance();

            int nCount = *(int*)&strAction.data()[0];

            QString str = &strAction.data()[4];

            str.resize(nCount);

            msgClient.ProcessAction(m_pTcpSock, str);
        }
    );
}

void HChatMainDlg::OnQueryUserNameResult(bool isOk, QString const& errMsg)
{
    if (!isOk)
    {
        ui->textEditShowMsg->append(tr("错误: %1").arg(errMsg));
        return;
    }
}

void HChatMainDlg::OnLoginResult(bool isOk, QString const& userName, QString const& token, QString const& errMsg)
{
    if (!isOk)
    {
        ui->textEditShowMsg->append(tr("错误: %1").arg(errMsg));
        return;
    }

    ui->textEditShowMsg->append(tr("用户 %1 登陆成功").arg(userName));
    m_ClientToken = token;

    ui->lineEditUserName->setReadOnly(true);
    ui->lineEditIP->setReadOnly(true);
    ui->lineEditPort->setReadOnly(true);
    ui->pushButtonConnect->setEnabled(false);
    
    HMsgManager& msgMgr = HMsgManager::GetInstance();
    msgMgr.RefreshUserList(m_pTcpSock, userName, token);

    m_GetUserListTimerId = startTimer(5000);
}

void HChatMainDlg::timerEvent(QTimerEvent* event)
{
    int timerId = event->timerId();
    if (timerId == m_GetUserListTimerId)
    {
        HMsgManager& msgMgr = HMsgManager::GetInstance();
        msgMgr.RefreshUserList(m_pTcpSock, ui->lineEditUserName->text(), m_ClientToken);
    }
}

void HChatMainDlg::OnGetUserInfoListResult(QString const& userName, QString const& token, QVector<UserInfo> const& userInfoList)
{
    ui->listWidgetUserList->clear();

    ui->listWidgetUserList->addItem(new QListWidgetItem(userName));

    for (auto user : userInfoList)
    {
        if (user.userName == userName)
        {
            continue;
        }

        ui->listWidgetUserList->addItem(new QListWidgetItem(user.userName));
    }
}

void HChatMainDlg::OnGetUserMessage(QString const& userName, QString const& msg)
{
    QString showText = tr("%1: %2").arg(userName).arg(msg);
    ui->textEditShowMsg->append(showText);
}

void HChatMainDlg::InitSlotFun()
{
    connect(ui->pushButtonSend, &QPushButton::clicked, this, &HChatMainDlg::OnSendMessage);
    connect(ui->pushButtonConnect, &QPushButton::clicked, this, &HChatMainDlg::OnConnectSrv);

    HMsgManager& msgClient = HMsgManager::GetInstance();
    connect(&msgClient, &HMsgManager::sigQueryUserNameResult, this, &HChatMainDlg::OnQueryUserNameResult);
    connect(&msgClient, &HMsgManager::sigLoginResult, this, &HChatMainDlg::OnLoginResult);
    connect(&msgClient, &HMsgManager::sigGetUserInfoListResult, this, &HChatMainDlg::OnGetUserInfoListResult);
    connect(&msgClient, &HMsgManager::sigGetUserMessage, this, &HChatMainDlg::OnGetUserMessage);
}

void HChatMainDlg::CloseConnection()
{
    if (m_pTcpSock == nullptr)
    {
        return;
    }

    m_pTcpSock->disconnectFromHost();

    m_pTcpSock->close();

    delete m_pTcpSock;

    m_pTcpSock = nullptr;
}
